import axios from 'axios'
import { MessageBox, Message, alert } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router  from "./../router/index.js";
import md5 from '@/utils/md5'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// request拦截器
service.interceptors.request.use(config => {
  let curParams = {};
  let str = ''
  if (config['data']) {
    config.data['token'] = getToken()
    // console.log(config.data)
    return config
  }

  if (store.getters.token) {
    if (config.params) {
      curParams['token'] = getToken();
    }
  }
  // console.log('config', config.data)
  if (config.params) {
    for (let key in config.params) {
      curParams[key] = config.params[key];
    }
    var keyArray = Object.keys(curParams).sort();

    for (let i = 0; i < keyArray.length; i++) {
      try {
        if (typeof JSON.parse(config.params) == "object") {
        } else {
          console.warn(curParams[keyArray[i]]+'+');
          str += keyArray[i] + '=' + curParams[keyArray[i]] + '&'
        }
      } catch (e) {
        console.warn(curParams[keyArray[i]]+'-');
        str += keyArray[i] + '=' + curParams[keyArray[i]] + '&'
      }
      // console.log('E', keyArray[i], curParams[keyArray[i]])
    };
    if (str) {
      str = str + 'secret=e1cd4b41ae55d4a7';
    } else {
      str = '&secret=e1cd4b41ae55d4a7';
    }
    // console.log('str', str, 1111111111,)
    let sign = '';
    if (str) {
      var reg = /[\u4e00-\u9fa5]/g;
      str = str.replace(reg, '');
      sign = md5(str)
      curParams.sign = sign
    }


  }
  if (config['data']) {
    config.data['token'] = getToken()
    // console.log(config.data)
    return config
  }

  if (store.getters.token) {

    if (config.params) {
      // config.params['token'] = getCookie('token')
      // config.params['no_check_sign'] = 1
      curParams['token'] = getToken();
      // no_check_sign = 1
    }
  }
  config.params = {};
  config.params = curParams;
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    res.msg = res.message //  后端更新数据结果，这里做了处理
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      // Token过期或者不合法
      if (res.code == -99 ) {
        Message({
          message: '登录失效，请退出后重新登录！' || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      if (res.code == -1 || res.code == -3 || res.code == -4 || res.code == -5){
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      if (res.code == 400 || res.code == 500){
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        // store.dispatch('user/resetToken').then(() => {
        //   location.reload()
        // })
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014 ) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
     console.log('err' + error) // for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // return Promise.reject(error)
  }
)

export default service
